package kr.co.creativeideas.gooq.common;

import java.util.Timer;
import java.util.TimerTask;

import android.util.Log;

public class StopWatch {

	public static final String EVENT_START = "watch.start";
	public static final String EVENT_STOP = "watch.stop";
	public static final String EVENT_SPLIT = "watch.split";
	public static final String EVENT_UNSPLIT = "watch.unsplit";
	public static final String EVENT_RESET = "whatch.reset";

	private int hr, min, sec, fract, fract10, fract100;
	private int dhr, dmin, dsec, dfract, dfract10, dfract100;
	private boolean split;
	private Timer timer;
	private static final String DELIM = ":";
	private static final String DOT = ".";
	private static final String EMPTY = "";
	private static final String ZERO = "0";

	public StopWatch() {
		// super(StopWatch.class.getClassLoader().getResource("kr/co/creativeideas/gooq/common/Stopwatch.xml"));
	}

	public void reset() {
		hr = min = sec = fract = dhr = dmin = dsec = dfract =dfract10 = dfract100 = 0;
		split = false;
	}

	public void running() {
		Log.i("timer", "start");
		split = false;
		if (timer == null) {
			timer = new Timer(true);
			timer.scheduleAtFixedRate(new TimerTask() {
				public void run() {
					increment();
				}
			}, 1, 1);
		}
	}

	public void paused() {
		split = true;
	}

	public void stopped() {
		timer.cancel();
		timer = null;
	}

	// used by the demonstration (see StopWatchDisplay usecase)
	// public String getCurrentState() {
	// Set states = getEngine().getCurrentStatus().getStates();
	// return ((org.apache.commons.scxml.model.State)
	// states.iterator().next()).getId();
	// }

	public String getDisplay() {
		String padhr = dhr > 9 ? EMPTY : ZERO;
		String padmin = dmin > 9 ? EMPTY : ZERO;
		String padsec = dsec > 9 ? EMPTY : ZERO;
		return new StringBuffer().append(padhr).append(dhr).append(DELIM)
				.append(padmin).append(dmin).append(DELIM).append(padsec)
				.append(dsec).append(DOT).append(dfract).append(dfract10).append(dfract100).toString();
	}

	private void increment() {
		if (fract100 < 9) {
			fract100++;
		} else {
			fract100 = 0;
			if (fract10 < 9) {
				fract10++;
			} else {
				fract10 = 0;
				if (fract < 9) {
					fract++;
				} else {
					fract = 0;					
					if (sec < 59) {
						sec++;
					} else {
						sec = 0;
						if (min < 59) {
							min++;
						} else {
							min = 0;
							if (hr < 99) {
								hr++;
							} else {
								hr = 0; // wrap
							}
						}
					}
				}
			}
		}
		if (!split) {
			dhr = hr;
			dmin = min;
			dsec = sec;
			dfract = fract;
			dfract10 = fract10;
			dfract100 = fract100;
		}
	}
}
